package com.xiaoyu.izf.service;

import com.google.common.collect.Lists;
import com.xiaoyu.izf.model.CommissionGetLog;
import com.xiaoyu.izf.model.UserInfo;
import com.xiaoyu.izf.model.page.DataTableBean;
import com.xiaoyu.izf.model.page.ParamListBean;
import com.xiaoyu.izf.repository.CommissionGetLogDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

@Service
public class CommissionGetLogService extends BaseService {

    @Autowired
    private CommissionGetLogDao commissionGetLogDao;
    @Autowired
    private UserInfoService userInfoService;

    public CommissionGetLog findById(int id){
        return commissionGetLogDao.findById(id);
    }

    public DataTableBean list(ParamListBean param) {
        PageRequest pageRequest = buildPageRequestSort(param.getPageNo(), param.getPageLength(), "id",param.getFieldName(),param.getCompositorType());

        //添加查询条件
        Page<CommissionGetLog> page = commissionGetLogDao.findAll(new Specification<CommissionGetLog>() {

            /**
             * 构建查询条件（Predicate断言对象）
             * @param root entity：UserInfo
             * @param query
             * @param cb 条件构建器
             * @return
             */
            @Override
            public Predicate toPredicate(Root<CommissionGetLog> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                //断言列表，可以添加多个断言
                List<Predicate> predicates = Lists.newArrayList();
                //准备结合断言链
                predicates.add(cb.conjunction());

                if (StringUtils.hasLength(param.getParam().get("payStatus"))){
                    //使用CriteriaBuilder条件构建器构建断言，并加入断言列表
                    predicates.add(
                            //断言为equals(期待值，实际值)，跟junit的断言类似
                            cb.equal(root.get("payStatus").as(Integer.class),param.getParam().get("payStatus")));
                }

                if (StringUtils.hasLength(param.getParam().get("uid"))){
                    //使用CriteriaBuilder条件构建器构建断言，并加入断言列表
                    predicates.add(
                            //断言为equals(期待值，实际值)，跟junit的断言类似
                            cb.equal(root.get("uid").as(Integer.class),param.getParam().get("uid")));
                }

                if (StringUtils.hasLength(param.getParam().get("userName"))){
                    //使用CriteriaBuilder条件构建器构建断言，并加入断言列表
                    predicates.add(
                            //断言为equals(期待值，实际值)，跟junit的断言类似
                            cb.equal(root.get("user").get("userName").as(String.class),param.getParam().get("userName")));
                }

                //断言列表加入断言，返回Predicate断言对象，交给jpa执行查询
                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        },pageRequest);

//		//无查询条件
//		Page<UserInfo> page = userInfoDao.findAll(pageRequest);

        return dataTableBean(page,param);
    }

    /**
     * 打款
     * @param getLog
     * @return
     */
    @Transactional
    public boolean commissionPay(CommissionGetLog getLog){
        if (canBePaid(getLog)){
            //改变提现记录状态
            getLog.setPayStatus(2);
            save(getLog);

            UserInfo userInfo = userInfoService.adminUserOne(getLog.getUid());
            int amount = getLog.getTotAmount();
            if (userInfo!=null){
                //设置提现相关金额
                userInfo.setCommission(userInfo.getCommission()-amount);
                userInfo.setCommissionPaying(userInfo.getCommissionPaying()-amount);
                userInfo.setCommissionPaid(userInfo.getCommissionPaid()+amount);
                userInfoService.save(userInfo);
                return true;
            }
        }
        return false;
    }

    private boolean canBePaid(CommissionGetLog getLog){
        return getLog!=null&&getLog.getPayStatus()==0;
    }

    @Transactional
    public CommissionGetLog save(CommissionGetLog getLog){
        return commissionGetLogDao.save(getLog);
    }
}
